package com.xzuf.nc;

import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author xzgf
 * @since 2008-9-25
 * @version 1.0
 */
public class MyTableModel extends DefaultTableModel {
	
	private static final int COLUMNCOUNT = 3;

	private Vector<TempletSchemeVO> dataList = new Vector<TempletSchemeVO>();
	
	public MyTableModel() {
		dataList = new Vector<TempletSchemeVO>();
	}
	
	public void addRow(TempletSchemeVO dataRow) {
		insertRow(getRowCount(),dataRow);
	}
	
	public void insertRow(int row,TempletSchemeVO dataRow) {
		if(dataRow != null && StringUtils.isNotEmpty(dataRow.getXmlTag())) {
			dataList.insertElementAt(dataRow, row);
			fireTableRowsInserted(row, row);
		}
	}
	
	@Override
	public void removeRow(int row) {
		dataList.removeElementAt(row);
	    fireTableRowsDeleted(row, row);
	}
	
	public void clearBodyData() {
		dataList.clear();
		fireTableRowsDeleted(0, getRowCount());
	}
	
	@Override
	public String getColumnName(int column) {
		if(column == 0) {
			return "模板字段";
		} else if(column == 1) {
			return "字段";
		} else if(column == 2) {
			return "缺省值";
		}
		return "";
	}
	
	@Override
	public int getRowCount() {
		if(dataList != null)
			return dataList.size();
		else
			return 0;
	}
	
	@Override
	public int getColumnCount() {
		return COLUMNCOUNT;
	}
	
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		if(columnIndex == 0) {
			return String.class;
		} else if(columnIndex == 1) {
			return JComboBox.class;
		}
		return super.getColumnClass(columnIndex);
	}
	
	@Override
	public Object getValueAt(int row, int column) {
		if(row >= 0 && row < dataList.size()) {
			TempletSchemeVO vo = dataList.get(row);
			if(column == 0) {
				return vo.getXmlTag();
			} else if(column == 1) {
				return vo.getValueField() == null ? "" : vo.getValueField();
			} else if(column == 2) {
				return vo.getDefaultValue() == null ? "" : vo.getDefaultValue();
			}
		}
		return "";
	}
	
	@Override
	public void setValueAt(Object value, int row, int column) {
		if(column == 1 && row < dataList.size()) {
			TempletSchemeVO vo = dataList.get(row);
			vo.setValueField(String.valueOf(value));
		} else if(column == 2 && row < dataList.size()) {
			TempletSchemeVO vo = dataList.get(row);
			vo.setDefaultValue(String.valueOf(value));
		}
		fireTableRowsInserted(row, row);
	}
	
	@Override
	public boolean isCellEditable(int row, int column) {
		if(column == 0) 
			return false;
		else
			return true;
	}
}
